package com.werdior.common.advice;

import com.werdior.common.exception.weirdorException;
import com.werdior.common.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;


/**
 * Created by weirdor on 2017/12/27.
 */
@ControllerAdvice
public class BaseMultiController {

    private static final Logger LOG = LoggerFactory.getLogger(BaseMultiController.class);

    private static final int TIP_SIZE = 10;

    @Autowired
    protected HttpServletRequest request;


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public R handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        LOG.error("缺少请求参数", e);
        return R.error("required_parameter_is_not_present");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        LOG.error("参数解析失败", e);
        return R.error("could_not_read_json");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        LOG.error("参数验证失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return R.error(message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public R handleBindException(BindException e) {
        LOG.error("参数绑定失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return R.error(message);
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public R handleServiceException(ConstraintViolationException e) {
        LOG.error("参数验证失败", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        return R.error("parameter:" + message);
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public R handleValidationException(ValidationException e) {
        LOG.error("参数验证失败", e);
        return R.error("validation_exception");
    }

    /**
     * 操作数据库出现异常:名称重复，外键关联
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DataIntegrityViolationException.class)
    public R handleException(DataIntegrityViolationException e) {
        LOG.error("操作数据库出现异常:", e);
        return R.error("操作数据库出现异常：字段重复、有外键关联等");
    }


    @ResponseBody
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e)
            throws Exception {
        /**
         if (e instanceof MissingFormatArgumentException
         || e instanceof MissingServletRequestParameterException
         || e instanceof IllegalArgumentException
         || e instanceof HttpMessageNotReadableException) {
         LOG.debug(e.getMessage(), e);
         return R.error(StringUtils.isBlank(e.getLocalizedMessage())? "参数缺失": e.getLocalizedMessage());
         }
         */
        if(e instanceof DuplicateKeyException){
            LOG.debug(e.getMessage(), e);
            return R.error("数据已经存在");
        }
        if(e instanceof IllegalStateException){
            LOG.debug(e.getMessage(), e);
            return R.error(e.getLocalizedMessage());
        }
        if(e instanceof weirdorException) {
            LOG.debug(e.getMessage(), e);
            return R.error(e.getLocalizedMessage());
        }
        LOG.error(e.getLocalizedMessage(), e);
        return R.error("网络连接错误,请稍后重试..");
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        binder.registerCustomEditor(String.class, new StringEscapeEditor());
    }

    private class StringEscapeEditor extends PropertyEditorSupport {
        public StringEscapeEditor() {}

        @Override
        public String getAsText() {
            Object value = getValue();
            return value != null ? value.toString() : "";
        }

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (text == null) {
                setValue(null);
            } else {
                setValue(HtmlUtils.htmlEscape(text));
            }
        }
    }

}
